<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="merchantName" label="商家名称">
          <el-input
            v-model="queryParams.merchantName"
            placeholder="商家名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item prop="contactName" label="联系人姓名">
          <el-input
            v-model="queryParams.contactName"
            placeholder="联系人姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item prop="contactEmail" label="联系人邮箱">
          <el-input
            v-model="queryParams.contactEmail"
            placeholder="联系人邮箱"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item prop="contactPhone" label="联系人电话">
          <el-input
            v-model="queryParams.contactPhone"
            placeholder="联系人电话"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option label="活跃" value="ACTIVE" />
            <el-option label="禁用" value="DISABLED" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            class="!w-[240px]"
            v-model="dateTimeRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="businessQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="businessList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商家名称" prop="merchantName" width="150" />
        <el-table-column label="联系人姓名" prop="contactName" width="150" />
        <el-table-column label="联系人邮箱" prop="contactEmail" width="150" />
        <el-table-column label="联系人电话" prop="contactPhone" width="150" />
        <el-table-column label="商家地址" prop="address" min-width="100" />
        <el-table-column label="注册日期" prop="registrationDate" width="150" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'ACTIVE'" type="success"
              >活跃</el-tag
            >
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="businessFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商家名称" prop="merchantName">
          <el-input
            v-model="formData.merchantName"
            placeholder="请输入商家名称"
          />
        </el-form-item>

        <el-form-item label="联系人姓名" prop="contactName">
          <el-input
            v-model="formData.contactName"
            placeholder="请输入联系人姓名"
          />
        </el-form-item>

        <el-form-item label="联系人邮箱" prop="contactEmail">
          <el-input
            v-model="formData.contactEmail"
            placeholder="请输入联系人邮箱"
          />
        </el-form-item>

        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input
            v-model="formData.contactPhone"
            placeholder="请输入联系人电话"
          />
        </el-form-item>

        <el-form-item label="商家地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入商家地址" />
        </el-form-item>

        <el-form-item label="商家状态" prop="status">
          <el-select v-model="formData.status">
            <el-option :key="0" label="活跃" :value="'ACTIVE'" />
            <el-option :key="1" label="禁用" :value="'DISABLED'" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getBusinessPage,
  updateBusiness,
  getBusinessForm,
  addBusiness,
  deleteBusinesss,
} from "@/api/business";
import {
  BusinessPageVO,
  BusinessForm,
  BusinessQuery,
} from "@/api/business/types";

defineOptions({
  name: "Business",
  inheritAttrs: false,
});

const dateTimeRange = ref(undefined);
const queryFormRef = ref(ElForm);
const businessFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startRegistrationDate = newVal[0];
    queryParams.endRegistrationDate = newVal[1];
  }
});

const queryParams = reactive<BusinessQuery>({
  pageNum: 1,
  pageSize: 10,
});

const businessList = ref<BusinessPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<BusinessForm>({
  id: undefined,
});

const rules = reactive({
  merchantName: [
    { required: true, message: "请输入商家名称", trigger: "blur" },
  ],
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
  ],
  contactEmail: [
    { required: true, message: "请输入联系人邮箱", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入联系人电话", trigger: "blur" },
  ],
  address: [{ required: true, message: "请输入商家地址", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getBusinessPage(queryParams)
    .then(({ data }) => {
      businessList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置查询 */
function businessQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  dateTimeRange.value = undefined;
  queryParams.startRegistrationDate = undefined;
  queryParams.endRegistrationDate = undefined;
  handleQuery();
}

/** 行checkbox 选中事件 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 打开商家表单弹窗 */
function openDialog(roleId?: number) {
  dialog.visible = true;
  if (roleId) {
    dialog.title = "修改角色";
    getBusinessForm(roleId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增角色";
  }
}

/** 角色保存提交 */
function handleSubmit() {
  businessFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const Id = formData.id;
      if (Id) {
        updateBusiness(Id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            businessQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addBusiness(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            businessQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  businessFormRef.value.resetFields();
  businessFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = undefined;
}

/** 删除角色 */
function handleDelete(roleId?: number) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteBusinesss(roleIds)
      .then(() => {
        ElMessage.success("删除成功");
        businessQuery();
      })
      .finally(() => (loading.value = false));
  });
}
onMounted(() => {
  handleQuery();
});
</script>
